import os
import ConfigParser


class ConfigError(Exception):
	''' config file exception file '''
	pass
	
	
class DefaultConfig:
	def __init__(self):
		pass

class Config(object):
	defaultServerSetting={
		'user':'',
		'port':'',
		'datadir':'',
		'initfile':'',		
	}
	defaultClientSetting={}
	
	def __init__(self,conf=''):		
		if conf == '':
			confFile = self._getConfigFile()
		elif self._validateFile(conf):
			confFile=conf
		else:
			confFile = None
			raise ConfigError("Can't find config file ")
		self.config = ConfigParser.ConfigParser()
		try:
			self.config.readfp(open(confFile))
		except:
			raise ConfigError('Fail to open config file')
	
	def _getConfigFile(self):
		'''
			find default config file if we didn't provide config information through parameters
		'''
		if os.name == 'nt':
			if os.path.exists('c:\\hirosql.cfg'):
				return 'c:\\hirosql.cfg'
			else:
				return './hirosql.cfg'
		elif os.name == 'posix':
			if os.path.exists('/etc/hirosql.cfg'):
				return '/etc/hirosql.cfg'
			else:
				return './hirosql.cfg'
		else:
			raise ConfigError('Unknown Operating System')
	
	def _validateFile(self,file):
		if os.path.exists(file) and os.access('file', os.R_OK):
			return True
		return False
		
	def loadServer(self):
		for i in self.config.items('server'):
			Config.defaultServerSetting[i[0]]=i[1]
		return Config.defaultServerSetting
		
	def loadClient(self):
		self.defaultServerSetting={}
		for i in self.config.items('client'):
			self.defaultServerSetting[i[0]]=i[1]
		return self.defaultServerSetting
		
if __name__ == '__main__':
	a=Config()
	a.loadServer()
	#print a.loadServer()
	print Config.defaultServerSetting
		
		